/*
 * File     : DynamicLibrary.java
 * Created  : 21 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.library;

import static com.googlecode.dni.internal.DniInternal.LOGGER;

import java.util.concurrent.atomic.AtomicBoolean;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.type.LifetimeManagedObject;
import com.googlecode.dni.type.NativeObject;
import com.googlecode.dni.type.Pointer;


/**
 * <p>
 *  Encapsulates a dynamic library.
 * </p>
 *
 * @author Matthew Wilson
 */
public final class DynamicLibrary implements LifetimeManagedObject
{

    private final long handle;

    /**
     * Whether the instance is disposed.  It's not 100% thread-safe; a
     * concurrent call to {@link #free()} and {@link #getSymbol(String)} would
     * kill it, but it's better than nothing.
     */
    private final AtomicBoolean disposed = new AtomicBoolean();


    private DynamicLibrary( final long handle )
    {
        assert handle != 0;
        this.handle = handle;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Pointer pointer()
    {
        return new Pointer( this.handle );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSameObject( final NativeObject other )
    {
        return other.getClass() == DynamicLibrary.class && other.pointer().getAddress() == this.handle;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void free()
    {
        if ( this.disposed.compareAndSet( false, true ) )
        {
            synchronized ( DynamicLibrary.class )
            {
                freeImpl( this.handle );
            }
        }
    }

    /**
     * <p>
     *  Looks up a symbol by name.
     * </p>
     *
     * @param name
     *            the name
     *
     * @return the symbol's pointer
     *
     * @throws SymbolNotFoundException
     *             if the symbol cannot be found
     */
    public Pointer getSymbol( final String name )
        throws SymbolNotFoundException
    {
        if ( this.disposed.get() )
        {
            throw new IllegalStateException();
        }

        long address;

        // depressingly, dlerror isn't thread-safe
        synchronized ( DynamicLibrary.class )
        {
            address = getSymbolImpl( this.handle, name );
        }

        if ( address == 0 )
        {
            throw new SymbolNotFoundException( name );
        }

        return new Pointer( address );
    }

    /**
     * Opens a dynamic library.
     *
     * @param name
     *            the name or location of the library
     * @return the library
     */
    public static DynamicLibrary open( final String name )
    {
        return open( name, false );
    }

    /**
     * Opens a dynamic library.
     *
     * @param name
     *            the name or location of the library
     * @param mangle
     *            whether to mangle the library name to fit platform standards
     * @return the library
     */
    public static DynamicLibrary open( final String name, final boolean mangle )
    {
        long handle;

        String mangledName = name;
        if ( name == null || name.isEmpty() )
        {
            mangledName = null;
        }
        else if ( mangle )
        {
            mangledName = DniInternal.PLATFORM.mangleLibraryName( name );
        }

        LOGGER.info( "Opening library: " + name );

        synchronized ( DynamicLibrary.class )
        {
            handle = openImpl( mangledName );
        }

        if ( handle == 0 )
        {
            throw new UnsatisfiedLinkError( "Cannot load library: " + name );
        }

        return new DynamicLibrary( handle );
    }

    private static native long openImpl( String name );

    private static native void freeImpl( long handle );

    private static native long getSymbolImpl( long handle, String name );

}
